/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.erpnasajon.dao;

import br.com.erpnasajon.modelo.Cliente;
import br.com.erpnasajon.utils.HibernateUtil;
import java.util.List;
import java.util.Map;
import org.hibernate.Transaction;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.primefaces.model.SortOrder;

/**
 *
 * @author MENDONCA
 */
public class ClienteDaoImp implements ClienteDao {
    @Override
    public void save(Cliente cliente){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = session.beginTransaction();
        try{
            //Trata as strings vazias
            if (cliente.getCpf().equals("")){
                cliente.setCpf(null);
            }
            if (cliente.getCnpj().equals("")){
                cliente.setCnpj(null);
            }
            
            session.save(cliente);
            transacao.commit();
        }
        catch(HibernateException he){
            transacao.rollback();
            throw he;
        }
        finally{
            session.close();
        }
            
    }
    @Override
    public Cliente getCliente(long id){
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            return (Cliente) session.load(Cliente.class, id);
        }
        finally{
            session.close();
        }
    }
    @Override
    public List<Cliente> list(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            return session.createQuery("from clientes").list();
        }
        finally{
            session.close();
        }            
    }
    @Override
    public void remove(Cliente cliente){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = session.beginTransaction();
        try{
            session.delete(cliente);
            transacao.commit();
        }
        catch(HibernateException he){
            transacao.rollback();
            throw he;
        }
        finally{
            session.close();
        }    
    }
    @Override
    public void update(Cliente cliente){    
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = session.beginTransaction();
        try{
            //Trata as strings vazias
            if (cliente.getCpf().equals("")){
                cliente.setCpf(null);
            }
            if (cliente.getCnpj().equals("")){
                cliente.setCnpj(null);
            }
            
            session.update(cliente);
            transacao.commit();
        }
        catch(HibernateException he){
            transacao.rollback();
            throw he;
        }
        finally{
            session.close();
        }   
    }
    @Override
    public List<Cliente> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            System.out.println("PARAM1 " +first);
            System.out.println("PARAM2 " +pageSize);
            Criteria criteria = session.createCriteria(Cliente.class);
            //Paginação
            criteria.setFirstResult(first);
            criteria.setFetchSize(pageSize);
            //Ordenacao
            if ((sortField != null) && (sortOrder != null)) {
                switch(sortOrder) {
                    case ASCENDING :
                        criteria.addOrder(org.hibernate.criterion.Order.asc(sortField)); 
                        break;
                    case DESCENDING :
                        criteria.addOrder(org.hibernate.criterion.Order.desc(sortField));
                        break;
                }
            }
            //Filtro - Obs: Tem que fazer o mesmo no metodo que retorna a quantidade [rowCount]
            if (filters != null){
                for (Map.Entry<String, String> entry : filters.entrySet()) {
                    /*
                    if (entry.getKey().equals("avaliacao")){
                        criteria.add( Restrictions.eq(entry.getKey(), Integer.parseInt(entry.getValue()) ) );
                    }
                    else { */
                        criteria.add(Restrictions.ilike(entry.getKey(), entry.getValue(), MatchMode.START));
                    //}
                }
            }
            
            return criteria.list();
        }
        finally{
            session.close();
        }             
    }
    @Override
    public int rowCount(Map<String, String> filters){
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            Criteria criteria = session.createCriteria(Cliente.class);
            criteria.setProjection(Projections.rowCount());
            
            //Filtro - Obs: Tem que fazer o mesmo no metodo que retorna a quantidade [rowCount]
            if (filters != null){
                for (Map.Entry<String, String> entry : filters.entrySet()) {
                    /*
                    if (entry.getKey().equals("avaliacao")){
                        criteria.add( Restrictions.eq(entry.getKey(), Integer.parseInt(entry.getValue()) ) );
                    }
                    else { */
                        criteria.add(Restrictions.ilike(entry.getKey(), entry.getValue(), MatchMode.START));
                    //}
                }
            }
            
            System.out.println(criteria.uniqueResult());
            return (Integer) criteria.uniqueResult();
        }
        finally{
            session.close();
        }
    }
}
